import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final _usernameController = TextEditingController();
  final _passwordController = TextEditingController();

  Future<void> _login() async {
    var url = Uri.parse("http://124.93.196.45:10091/prod-api/api/login");
    var headers = {"Content-Type": "application/json"};
    var body = jsonEncode({
      "username": _usernameController.text,
      "password": _passwordController.text
    });
    var req = await http.post(url, body: body, headers: headers);
    var resp = jsonDecode(utf8.decode(req.bodyBytes));
    print(resp);
    print(resp['code']);

    if (resp['code'] == 200) {
      print('yes');
      ScaffoldMessenger.of(context)
          .showSnackBar(SnackBar(content: Text("登录成功")));
      Navigator.of(context).pushReplacementNamed('/main');
    } else {
      ScaffoldMessenger.of(context)
          .showSnackBar(SnackBar(content: Text("登陆失败：${resp['msg']}")));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('智慧城市'),
      ),
      body: Padding(
        padding: EdgeInsets.all(16.0),
        child: Column(
          children: [
            TextField(
              controller: _usernameController,
              decoration: InputDecoration(labelText: '用户名'),
            ),
            TextField(
              controller: _passwordController,
              decoration: InputDecoration(labelText: '密码'),
              obscureText: true,
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _login,
              child: Text('登录'),
            ),
          ],
        ),
      ),
    );
  }
}
